import {Message} from 'element-ui';
import {baseUrl} from '@/config';
import {storageLocal} from '@/common/utils/storage';

/**
 * 封装fetch
 * @param url
 * @param opt {method, headers, body, type, ...rest}
 * @returns {Promise<any>}
 */
export default function fetchApi(url, opt) {
    const isObj = obj => Object.prototype.toString.call(obj) === '[object Object]';
    return new Promise((resolve, reject) => {
        if (!isObj(opt)) {
            opt = {};
        }
        const {headers: initHeaders, method, body: initBody, type} = opt;
        const token = storageLocal.get('token');
        let headers = new Headers({token});
        if (isObj(initHeaders)) {
            for (let k in initHeaders) {
                headers.set(k, initHeaders[k]);
            }
        }
        let body = '';
        if (!type || type === 'json') {
            headers.set('Content-Type', 'application/json;charset=UTF-8');
            initBody.token = token;
            body = JSON.stringify(initBody);
        } else if (type === 'file') {
            let form = new FormData();
            for (let k in initBody) {
                if (typeof initBody[k] !== 'undefined') {
                    form.append(k, initBody[k]);
                }
            }
            body = form;
        }
        if (!/^(https?):\/\//.test(url)) {
            url = baseUrl + url;
        }
        const req = new Request(url, {
            method: 'POST',
            mode: 'cors',
            cache: 'default',
            // credentials: 'include',
            body,
            headers,
        });
        fetch(req).then(res => {
            if (!res.ok) {
                reject();
                return false;
            }
            res.json().then(json => {
                if (json.code === '000000') {
                    resolve(json);
                    return false;
                }
                // if (json.code === '001') {
                //     let timer = setTimeout(() => {
                //         clearTimeout(timer);
                //         location.href = '/login';
                //     }, 1500);
                //     Message.error('登录超时, 请重新登录');
                //     return false;
                // }
                Message.error(json.message);
                reject(json.message);
            });
        }).catch(err => {
            reject(err);
        });
    });
}
